using System;
using System.Xml;
using System.IO;

namespace SoftwareMonkeys.Scriptech.Projects
{
	public class ProjectAssemblyConverter
	{
		public ProjectAssemblyConverter ()
		{
		}
		
		public ProjectAssembly ConvertFromNAnt(string assemblyPropertiesPath, Project project)
		{
			XmlDocument document = new XmlDocument();
			document.Load(assemblyPropertiesPath);
			
			ProjectAssembly assembly = new ProjectAssembly();
						
			assembly.Name = GetPropertyValue(document, "Name");
			assembly.BaseNamespace = GetPropertyValue(document, "BaseNamespace");
			assembly.OutputFileName = GetPropertyValue(document, "AssemblyName");
			assembly.Directory = project.GroupName + "." + assembly.Name;
			
			return assembly;
		}
		
		public bool IsAssembly(string nantFilePath)
		{
			string fileName = Path.GetFileName(nantFilePath);
			
			return fileName.ToLower().IndexOf(".assembly.nant") > -1;
		}
		
		private XmlNode GetPropertyNode(XmlDocument document, string propertyName)
		{
			foreach (XmlNode node in document.DocumentElement.ChildNodes)
			{
				if (node.Name != null
				    && node.Name.ToLower() == "property"
				    && node.Attributes["name"] != null && node.Attributes["name"].Value == "Assembly." + propertyName)
					return node;
			}
			
			return null;
		}
		
		private string GetPropertyValue(XmlDocument document, string propertyName)
		{
			string output = String.Empty;
			
			XmlNode node = GetPropertyNode(document, propertyName);
			if (node != null)
				output = node.Attributes["value"].Value;
			
			return output;
		}
	}
}

	